<?php

class DefaultController extends FController {

    public $user_school_list;
    public $user_subject_list;
    public $user_role_list;
    public $exam_id;

    public function accessRules() {
        $config = array('index' => 1);
        return ZRole::auth("notice", $config);
    }

    public function init() {
        parent::init();
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/base.css');
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/master.css');
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
    }

    public function __common() {
        parent::init();
        if (empty($this->cLoginUser)) {
            $this->redirect($this->createUrl('/site/login'));
        } else {
            $userLoginUser = $this->cLoginUser;

            $this->user_role_list = isset($userLoginUser['cuser']['role_id']) ? $userLoginUser['cuser']['role_id'] : '';
            $this->user_school_list = isset($userLoginUser['cuser']['school']['school_id']) ? $userLoginUser['cuser']['school']['school_id'] : '';
            $this->user_subject_list = isset($userLoginUser['cuser']['school']['subject_id']) ? $userLoginUser['cuser']['school']['subject_id'] : '';
            
            $zRow = new ZRole();
          
            //得到学校对应的考试
            $exam_list = $zRow->_getSchoolExam($this->user_school_list);
            if(!empty($exam_list)){
                $this->exam_id = implode(',', $exam_list);
            }
        }
        $this->commonScript();
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
      
    }
	
	
	
    public function actionIndex() {
        $this->__common();
        Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/jquery-1.8.3.js");
        Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/My97DatePicker/WdatePicker.js");
        $conn = Yii::app()->db;
        $this->title = '考试项目维护';

        $s ['exam_name'] = Yii::app()->request->getParam('exam_name');
        $s ['exam_term_id'] = Yii::app()->request->getParam('exam_term_id');
        $s ['exam_term_sx'] = Yii::app()->request->getParam('exam_term_sx');
        $s ['exam_start_time'] = Yii::app()->request->getParam('exam_start_time');
        $s ['exam_end_time'] = Yii::app()->request->getParam('exam_end_time');
        $s ['exam_status'] = Yii::app()->request->getParam('exam_status');

        $s = ZTask::dis_input($s);
        $s = Func::fAddslashes($s);
        $where = ' AND "is_del" = 0';
        $order = ' ORDER BY "time_created" DESC ';
        #  拼接条件  #
        if (Func::dis_search($s ['exam_name'])) {
            $where .= ' AND "exam_name" LIKE \'%' . $s ['exam_name'] . '%\'';
        }
        if (!empty($s ['exam_status'])) {
            $where .= ' AND "exam_status" = \'' . ($s ['exam_status'] - 1) . '\'';
        }
        if (!empty($s ['exam_start_time'])) {
            $start = strtotime($s ['exam_start_time']);
            $where .= ' AND "exam_start_time" >= \'' . $start . '\'';
        }
        if (!empty($s ['exam_end_time'])) {
            $end = strtotime($s ['exam_end_time']);
            $where .= ' AND "exam_end_time" <= \'' . $end . '\'';
        }
        if (!empty($s ['exam_term_id'])) {
            $s ['exam_term_ids'] = (!empty($s ['exam_term_sx'])) ? $s ['exam_term_id'] . '-' . $s ['exam_term_sx'] : $s ['exam_term_id'];
            $where .= ' AND "exam_term" LIKE \'%' . $s ['exam_term_ids'] . '%\'';
        }
        if (!empty($s ['exam_term_sx'])) {
            $where .= ' AND "exam_term" LIKE \'%' . $s ['exam_term_sx'] . '%\'';
        }
        
      
        //权限判断
        if ($this->user_role_list != 1 && !empty($this->exam_id)) {
            $where .= ' AND "exam_id" IN (' . $this->exam_id . ')';
        }
        $select = 'SELECT * FROM "{{exam}}" A';
        $sql = ' WHERE 1=1 ' . $where;
        $selectSql = $select . $sql . $order;
        $countSql = 'SELECT COUNT(*) FROM "{{exam}}" A ' . $sql;
        $data = ZCommon::getDaoPageList($selectSql, $countSql, 8);
        if (!empty($data ['listDatas'])) {
            $temp = $array = array();
            foreach ($data ['listDatas'] as $key => $value) {
                
                #  处理学年和学期  #
                $temp = explode('-', $value ['exam_term']);
                $temp ['exam_term'] = $temp [0];
                $temp ['exam_term_sx'] = ($temp [1] == 's') ? '第一学期' : '第二学期';

                #  取年级  #
                if (!empty($array ['grade'] [$value ['exam_edu_grade']])) {
                    $temp ['grade_name'] = $array ['grade'] [$value ['exam_edu_grade']];
                } else {
                    $gradeModel = EduGrade::model()->findByPk($value ['exam_edu_grade'], ' "disabled" = 1 AND "is_del" = 0');

                    if (!empty($gradeModel)) {
                        $array ['edu_term'] [$value ['exam_edu_grade']] = $temp ['grade_name'] = $gradeModel->grade_name;
                    } else {
                        $temp ['grade_name'] = $array['edu_term'][$value['exam_edu_grade']] = '没有年级';
                    }
                }
                $data ['listDatas'] [$key] = array_merge($data ['listDatas'] [$key], $temp);
            }
        }
        #  取所有的学年  #
        $examData = new ExamData ();
        $info ['eduTermData'] = $examData->_getGrade();
        $pageUrl = $this->createUrl('/exam/default/index', $s);
        $this->render('index', array('data' => $data ['listDatas'], 'pages' => $data ['pages'], 'pageUrl' => $pageUrl, 'info' => $info, 'search' => $s));
    }
	
	/**
	 * @ 添加考试项目
	 * @ yindebin
	 * @ 2013-12-14 AM
	 */
	public function actionAdd() {
		$this->__common ();
		$this->layout = "//layouts/main_window";
		$this->title = "新增考试项目";
		Yii::app ()->clientScript->registerScriptFile ( STATICS_URL . "/js/jquery-1.8.3.js" );
		Yii::app ()->clientScript->registerScriptFile ( STATICS_URL . "/js/My97DatePicker/WdatePicker.js" );
		$conn = Yii::app ()->db;
		$info = array ();
		if (! empty ( $_POST ['submit'] )) {
			$data = ZTask::dis_input($_POST ['info']);
		
			$data ['school'] = (! empty ( $_POST ['school'] )) ? $_POST ['school'] : '';
			if(empty($data['school'])){
				$this->frameAjaxMessage(null,'请选择学校');
				exit;
			}
			$data ['exam_subject_ids'] = (! empty ( $_POST ['subject'] )) ? implode ( '-', $_POST ['subject'] ) : '';
			if(empty($data['exam_subject_ids'])){
				$this->frameAjaxMessage(null,'请选择科目');
				exit;
			}
			$data ['exam_status'] = (! empty ( $data ['exam_status'] )) ? $data ['exam_status'] : '0';
			$data ['exam_term'] = (! empty ( $data ['exam_term_id'] ) && ! empty ( $data ['exam_term_sx'] )) ? $data ['exam_term_id'] . '-' . $data ['exam_term_sx'] : '';
			if(empty($data['exam_term'])){
				$this->frameAjaxMessage(null,'请选择学年');
				exit;
			}
			$data ['exam_start_time'] = (! empty ( $data ['exam_start_time'] )) ? strtotime ( $data ['exam_start_time'] ) : time();
			$data ['exam_end_time'] = (! empty ( $data ['exam_end_time'] )) ? strtotime ( $data ['exam_end_time'] ) : time();
			$data['create_user'] = $this->cLoginUser['cuser']['id'];
           	$data['create_time'] = time();
           	$data['update_user'] = $this->cLoginUser['cuser']['id'];
           	$data['update_time'] = time();
            $data['is_del'] = 0;
			
			#  拼接项目名称  #
			$exam_array = array ('s' => '第一学期', 'x' => '第二学期' );
			$data ['exam_term_name'] = $data ['exam_term_id'] . $exam_array [$data ['exam_term_sx']] . $data ['exam_name'];
			
			$check = Exam::model()->find('"exam_term_name" = \''.$data['exam_term_name'].'\'');
			if(!empty($check)){
				if($check->is_del == 1){
					$this->frameAjaxMessage(null,'相同的考试项目在回收站中,不可重复使用');
				}else{
					$this->frameAjaxMessage(null,'已存在相同的考试项目');
				}
				exit;
			}
			
			$data['exam_subject_type'] = (!empty($data['exam_subject_type'])) ? $data['exam_subject_type'] : 0;
			$data ['time_created'] = time ();
			$model = new Exam ();
			$model->attributes = $data;
			
			if ($model->save ()) {
				if (! empty ( $data ['school'] )) {
					$id = $model->attributes ['exam_id'];
					foreach ( $data ['school'] as $value ) {
						$sql = 'INSERT INTO "{{exam_school}}" VALUES('."'" . $id . "'".','."'" . $value . "'".')';
						$result = $conn->createcommand ( $sql )->execute ();
					}
				}
				$this->frameAjaxMessage ('index');exit;
			} else {
				$this->frameAjaxMessage(null,'添加失败');exit;
			}
			exit ();
		}

		$info = $this->_getNeedDatas ();
		$import = ZTask::_getimportrule();
		$this->render ( 'add', array ('info' => $info , 'import'=>$import) );
	}

	/**
	 * @ 更新考试项目
	 * @ yindebin
	 * @ 2013-12-14 AM
	 */

	public function actionUpdate() {
		Yii::app ()->clientScript->registerScriptFile ( STATICS_URL . "/js/My97DatePicker/WdatePicker.js" );
		$this->__common ();
		$this->layout = "//layouts/main_window";
		$exam_id = Yii::app ()->request->getParam ( 'exam_id' );
		$conn = Yii::app ()->db;
		$this->title = "编辑考试项目";
		$exam_id = (! empty ( $_POST ['info'] ['exam_id'] )) ? $_POST ['info'] ['exam_id'] : $exam_id;

		$examModel = Exam::model ()->findByPk ( $exam_id );
		if (empty ( $examModel )) {
			$this->frameAjaxMessage (  'index' ) ;exit;
			exit ();
		}

		if (! empty ( $_POST ['submit'] )) {
			$data = ZTask::dis_post($_POST ['info']);
		
		
			$data ['school'] = (! empty ( $_POST ['school'] )) ? $_POST ['school'] : 0;
			if(empty($data['school'])){
				$this->frameAjaxMessage(null,'请选择学校');
				exit;
			}
			$data ['exam_subject_ids'] = (! empty ( $_POST ['subject'] )) ? implode ( '-', $_POST ['subject'] ) : 0;
			if(empty($data['exam_subject_ids'])){
				$this->frameAjaxMessage(null,'请选择科目');
				exit;
			}
			$data ['exam_status'] = (! empty ( $data ['exam_status'] )) ? $data ['exam_status'] : 0;
			$data ['exam_term'] = (! empty ( $data ['exam_term_id'] ) && ! empty ( $data ['exam_term_sx'] )) ? $data ['exam_term_id'] . '-' . $data ['exam_term_sx'] : '';
			if(empty($data['exam_term'])){
				$this->frameAjaxMessage(null,'请选择学年');
				exit;
			}
			$data ['exam_start_time'] = (! empty ( $data ['exam_start_time'] )) ? strtotime ( $data ['exam_start_time'] ) : '';
			$data ['exam_end_time'] = (! empty ( $data ['exam_end_time'] )) ? strtotime ( $data ['exam_end_time'] ) : '';
           	$data['update_user'] = $this->cLoginUser['cuser']['id'];
           	$data['update_time'] = time();
			
			$exam_array = array ('s' => '第一学期', 'x' => '第二学期' );
			#  拼接项目名称  #
			$data ['exam_term_name'] = $data ['exam_term_id'] . $exam_array [$data ['exam_term_sx']] . $data ['exam_name'];
			
			$check = Exam::model()->find('"exam_term_name" = \''.$data['exam_term_name'].'\' AND "exam_id" != \''.$data['exam_id'].'\'');
			if(!empty($check)){
				if($check->is_del == 1){
					$this->frameAjaxMessage(null,'相同的考试项目在回收站中,不可重复使用');
				}else{
					$this->frameAjaxMessage(null,'已存在相同的考试项目');
				}
				exit;
			}
			
			$data['exam_subject_type'] = (!empty($data['exam_subject_type'])) ? $data['exam_subject_type'] : 0;
			
			#$model = new Exam();
			$examModel->attributes = $data;

			if ($examModel->save ()) {
				if (! empty ( $data ['school'] )) {
					$deleted = ExamSchool::model ()->deleteAll ( '"exam_id" = ' . $exam_id );
					foreach ( $data ['school'] as $value ) {
						$sql = 'INSERT INTO "{{exam_school}}" VALUES(\'' . $exam_id . '\',\'' . $value . '\')';
						$result = $conn->createcommand ( $sql )->execute ();
					}
				}
				$this->frameAjaxMessage (  'index' );
			} else {
				$this->frameAjaxMessage(null,'添加失败');
			}
			exit ();
		} else {
			#  整理数据  #
			$data = $examModel->attributes;
			$temp = explode ( '-', $data ['exam_term'] );
			$data ['exam_term_id'] = $temp [0];
			$data ['exam_term_sx'] = $temp [1];
			$data ['exam_subject_ids'] = explode ( '-', $data ['exam_subject_ids'] );

			$info = array ();
			$info = $this->_getNeedDatas ();
			#  取参加学校的id  #
			$examWhere = "";
			$examOrder = "";

			$examWhere.= ' AND "exam_id" = '.$exam_id;

			$examSelect = 'SELECT * FROM "{{exam_school}}"';
			$examSql = ' WHERE 1=1 ' ;
			$examSelectSql = $examSelect . $examSql . $examWhere;
			$info ['examDatas'] = $conn->createcommand ( $examSelectSql )->queryAll ();

			if (! empty ( $info ['examDatas'] )) {
				foreach ( $info ['examDatas'] as $dv ) {
					$data ['school_ids'] [] = $dv ['school_id'];
				}
			}
			$this->render ( 'update', array ('data' => $data, 'info' => $info ) );
		}
	}

	/**
	 * @ 获取年级
	 * @ yindebin
	 * @ 2013-12-14 AM
	 */
	public function actionGet_grade() {
		$this->__common ();
		$edu_id = Yii::app ()->request->getParam ( 'edu_id' );
		$grade_id = Yii::app ()->request->getParam ( 'grade_id' );
		$grade_id = (! empty ( $grade_id )) ? $grade_id : 0;
		
		$exam_id = Yii::app ()->request->getParam ( 'exam_id' );
		$exam_id = (! empty ( $exam_id )) ? $exam_id : 0;
		
		$array = array();
	    #  取年级id  #
		$array['school'] = "<h1>请选择年段</h1>";
		
		$array['grade'] = "<option value='0'>请选择</option>";
		if(!empty($edu_id)){
			$examData = new ExamData ();
			$grade_data = $examData->_getEduGrade ( $edu_id );

			foreach ( $grade_data as $value ) {

				if ($value ['grade_id'] == $grade_id) {
					$array['grade'] .= "<option value='" . $value ['grade_id'] . "' selected >" . $value ['grade_name'] . "</option>";
				} else {
					$array['grade'] .= "<option value='" . $value ['grade_id'] . "'>" . $value ['grade_name'] . "</option>";
				}
			}
			
			if(!empty($exam_id)){
				$esSql = 'SELECT "school_id" FROM "{{exam_school}}" WHERE "exam_id" = '.$exam_id;
				$esData = Yii::app()->db->createCommand($esSql)->queryAll();
				$esData = (!empty($esData)) ? $esData : array();
			}
			
			$sql = 'SELECT "school_id","school_code","school_name" FROM "{{school}}" WHERE "is_del" = 0 AND "disabled" = 1 AND "edu_type_ids" = '."'".$edu_id."'";
			$school = Yii::app()->db->createCommand($sql)->queryAll();
			if(!empty($school)){
				$array['school'] = '';
					foreach ($school as $k=>$v){
						$array['school'].= "<li class='fl pr12 pb5'><input type='checkbox' name='school[]' value='".$v['school_id']."' ><span class='pl5'>".$v['school_name']."</span></li>";
					}
				# }
			}
		}
		$array['school'] = urlencode($array['school']);
	
		echo urldecode(json_encode($array));
		exit ();
		
	}

	/**
	 * @ 删除考试项目
	 * @ yindebin
	 * @ 2013-12-14 AM
	 */
	public function actionDelete() {
		$this->__common ();
		$exam_id = ( int ) Yii::app ()->request->getparam ( 'exam_id' );

		if (! empty ( $exam_id )) {
			$model = Exam::model ()->findByPk ( $exam_id );
			if (empty ( $model )) {
				$this->redirect ( $this->createUrl ( 'index' ) );
				exit ();
			}
			$delete = 'UPDATE "{{exam}}" SET "is_del" = 1 WHERE "exam_id" = '.$exam_id;
			$query = Yii::app()->db->createCommand($delete)->execute();
			if ($query) {
				
				$this->redirect ( $this->createUrl ( 'index' ) );
				exit ();
			} else {
				$this->redirect ( $this->createUrl ( 'index' ) );
				exit ();
			}
		} else {
			$this->redirect ( $this->createUrl ( 'index' ) );
		}
	}
	/**
	* @ 批量删除
	* @ yindebin
	* @ 2014-01-06 pm
	*
	*/
	public function actionDelete_all(){
		$exam_id = Yii::app ()->request->getparam ( 'exam_id' );
		if (! empty ( $exam_id )) {
			$delete = 'UPDATE "{{exam}}" SET "is_del" = 1 WHERE "exam_id" IN ('.$exam_id.')';
			$query = Yii::app()->db->createCommand($delete)->execute();
			echo 1;
		}else{
			echo 2;
		}
	}
		
	public function _getNeedDatas() {
		$examData = new ExamData ();

		#  取所有学年  #
		$info ['eduTermData'] = $examData->_getGrade ();

		#  取所有学段  #


		$info ['xdDatas'] = $examData->_getEduType ();

		#  取所有学校  #


		# $info ['schoolDatas'] = $examData->_getSchool ();

		#  取所有科目  #


		$info ['subjectDatas'] = $examData->_getSubject ();

		return $info;
	}

}